using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using MyPhotoIndex.Settings;
using MyPhotoIndex.Utilities;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.Threading;
using MyPhotoIndex.UpdateCheckServiceProxy;

namespace MyPhotoIndex.VersionCheck
{
    public class VersionChecker
    {
        public event EventHandler<VersionCheckerEventArgs> VersionCheckResponseEvent;

        public void CheckForNewerVersionAsync()
        {
            CheckForNewerVersionAsync(null);
        }
     
        public void CheckForNewerVersionAsync(Object tag)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckForNewerVersionAsyncInternal), tag);
        }

        private void CheckForNewerVersionAsyncInternal(Object state)
        {
            if (state != null)
            {
                ApplicationContext.Instance.ProcessProgress.IsInfinite = true;
                ApplicationContext.Instance.ProcessProgress.Running = true;
            }

            VersionCheckerEventArgs eventArgs = new VersionCheckerEventArgs();
            UpdateCheckServiceProxy.UpdateInfo updateInfo;
            eventArgs.NewVersionExists = CheckForNewerVersion(out updateInfo);
            eventArgs.ProgramInfo = updateInfo;
            eventArgs.Tag = state;

            if (state != null)
            {
                ApplicationContext.Instance.ProcessProgress.Running = false;
            }

            if (VersionCheckResponseEvent != null)
            {
                VersionCheckResponseEvent.Invoke(this, eventArgs);
            }
        }

        public static bool CheckForNewerVersion(out UpdateInfo updateInfo)
        {
            updateInfo = null;

            try
            {
                ProductVersionInfo versionInfo = new ProductVersionInfo();

                Assembly asm = Assembly.GetExecutingAssembly();
                String versionString = String.Format("{0}.{1}.{2}", asm.GetName().Version.Major, asm.GetName().Version.Minor, asm.GetName().Version.Build);
                versionInfo.Version = versionString;
                versionInfo.InstallationId = ApplicationSettings.Default.InstallationId;
                versionInfo.ProductId = ApplicationSettings.Default.ProductId;

                UpdateService updateSerice = new UpdateService();
                UpdateInfo[] productsUpdateInfo = updateSerice.ChaeckForUpdates(new ProductVersionInfo[] { versionInfo });

                updateInfo = productsUpdateInfo[0];
                return updateInfo.UpdateAvailable;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }
    }
}
